//
//  NSString+Fantasia.m
//  Fantasia
//
//  Created by kongkong on 2016/11/1.
//  Copyright © 2016年 Kongkong. All rights reserved.
//

#import "NSString+Fantasia.h"
#import <CommonCrypto/CommonDigest.h>
#import <AdSupport/AdSupport.h>
#import <SSKeychain.h>

#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

static NSString* fakeUDID = @"";

@implementation NSString (Fantasia)

- (NSString *)md5
{
    // Create pointer to the string as UTF8
    const char* ptr = [self UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    // Create 16 byte MD5 hash value, store in buffer
    CC_MD5(ptr, (int)strlen(ptr), md5Buffer);
    
    // Convert MD5 value in the buffer to NSString of hex values
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x",md5Buffer[i]];
    }
    
    return output;
}

-(NSString *)trim{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

+ (NSString *)idfa
{
    NSString *idfa = nil;
    if (NSClassFromString(@"ASIdentifierManager")) {
        if (SYSTEM_VERSION_LESS_THAN(@"10") || [ASIdentifierManager sharedManager].isAdvertisingTrackingEnabled) {
            idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        }
    }
    return idfa;
}

+ (NSString *)udid
{
    if (fakeUDID.length) {
        return fakeUDID;
    }
    
    static NSString *accountName = @"fantasia.idfa";
    static NSString *serviceName = @"fantasia_udid_key";
    
    static dispatch_once_t onceToken;
    static NSString * uniqueId = nil;
    dispatch_once(&onceToken, ^{
        
        uniqueId = [SSKeychain passwordForService:serviceName account:accountName];
        
        if (uniqueId.length == 0) {
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
                uniqueId = [self idfa];
                
                if (uniqueId.length == 0) {//不存在说明用户关闭了广告跟踪
                    NSString *timeString = [NSString stringWithFormat:@"%.5f",[[NSDate date] timeIntervalSince1970]];
                    NSString *randomString = [NSString stringWithFormat:@"%d", arc4random() % 10000/*0-9999*/];
                    uniqueId = [[timeString stringByAppendingString:randomString] md5];
                }
            }
            [SSKeychain setPassword:uniqueId forService:serviceName account:accountName];
        }
        
    });
    
    return uniqueId;
}

@end
